<template>
  <div class="category-m-index">
    <div
      style="
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
      "
    >
      <Search
        :type="4"
        :pageParam="{ page: param.page, size: param.size }"
        :placeholder="'请输入游戏类别名进行搜索'"
        @searchResult="searchResult"
      />
      <div v-if="!isSelect" class="btn-group">
        <el-button type="primary" @click="dialogVisible = true">
          新增分类
        </el-button>
        <el-button type="danger" @click="isSelect = true"> 批量删除 </el-button>
      </div>
      <div v-else class="btn-group">
        <el-button type="primary" @click="handleDelete(null)"> 确定 </el-button>
        <el-button
          type="default"
          @click="(isSelect = false), toggleSelection()"
        >
          取消
        </el-button>
        <el-button
          v-if="multipleSelection.length > 0"
          type="default"
          @click="toggleSelection()"
        >
          清空所选项
        </el-button>
      </div>
    </div>
    <el-table
      ref="multipleTableRef"
      style="height: 100%"
      :data="gameCategoryList"
      stripe
      empty-text="暂无数据"
      show-overflow-tooltip
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        v-if="isSelect"
        type="selection"
        :selectable="selectable"
        width="55"
      />
      <el-table-column prop="categoryName" label="游戏分类名" width="180" />
      <el-table-column prop="description" label="类别描述" width="500" />
      <el-table-column
        fixed="right"
        label="操作"
        width="auto"
        min-width="180px"
        v-if="!isSelect"
      >
        <template #default="scoped">
          <el-button link type="primary" size="small">详情</el-button>
          <el-button link type="primary" size="small">编辑</el-button>
          <el-button
            link
            type="danger"
            size="small"
            @click="handleDelete(scoped.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-config-provider :locale="zhCn">
      <el-pagination
        layout="sizes, prev, pager, next, jumper"
        :page-count="pageCount"
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-config-provider>
    <el-dialog
      style="width: 30%"
      v-model="dialogVisible"
      title="新增分类"
      @keydown.enter="handleAddCategory"
    >
      <el-form :model="form" label-width="auto" label-position="right">
        <el-form-item label="分类名">
          <el-input v-model="form.categoryName" />
        </el-form-item>
        <el-form-item label="类别描述">
          <el-input v-model="form.description" />
        </el-form-item>
        <el-form-item>
          <el-button
            style="width: 48%"
            type="primary"
            @click="handleAddCategory"
          >
            确定
          </el-button>
          <el-button
            style="width: 48%; margin-left: auto"
            type="default"
            @click="handleClose"
          >
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  getCategoryList,
  addCategoryApi,
  deleteCategoryApi,
  // getCategoryApi,
} from "@/apis/category";
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import { ElConfigProvider } from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import Search from "@/components/sreach/index.vue";

const gameCategoryList = ref([]);

const pageCount = ref(0);

const dialogVisible = ref(false);

const selectable = (row: any) => row.id;

const isSelect = ref(false);

const param = ref({
  page: 1,
  size: 10,
});

const form = ref({
  categoryName: "",
  description: "",
});

const multipleSelection = ref([]);

const multipleTableRef = ref();

const toggleSelection = (rows?: any[], ignoreSelectable?: boolean) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTableRef.value!.toggleRowSelection(
        row,
        undefined,
        ignoreSelectable
      );
    });
  } else {
    multipleTableRef.value!.clearSelection();
  }
};

function handleSelectionChange(row?: any) {
  multipleSelection.value = row;
}

async function handleAddCategory() {
  const formData = new FormData();
  formData.append("categoryName", form.value.categoryName);
  formData.append("description", form.value.description);
  try {
    const res: any = await addCategoryApi(formData);
    if (res.code === 0) {
      form.value.categoryName = "";
      form.value.description = "";
      ElMessage.success("新增分类成功！");
      dialogVisible.value = false;
      await getGameCategoryListData(param.value);
    } else {
      ElMessage.error("新增分类失败！");
    }
  } catch (error) {
    console.log(error);
    ElMessage.error("新增分类失败！");
    dialogVisible.value = false;
  }
}

async function handleDelete(row: any) {
  let Api;
  let message;
  let deleteList;

  if (row === null) {
    deleteList = multipleSelection.value.map((item: any) => item.id);
    message = `确认删除所选分类吗？`;
    Api = deleteCategoryApi(deleteList);
  } else {
    deleteList = [row.id];
    Api = deleteCategoryApi(deleteList);
    message = `确认删除<span style='color:red'> ${row.categoryName} </span>分类吗？`;
  }

  try {
    await ElMessageBox.confirm(message, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
    });
    const res: any = await Api;
    if (res.code === 0) {
      ElMessage.success("删除分类成功！");
      gameCategoryList.value = gameCategoryList.value.filter(
        (item: any) => !deleteList.includes(item.id)
      );
      isSelect.value = false;
    } else {
      ElMessage.error("删除分类失败！");
    }
  } catch (error) {
    if (error === "cancel") {
      ElMessage.info("取消操作");
    } else {
      console.error("删除操作失败:", error);
      ElMessage.error("删除分类失败，请稍后重试！");
    }
  }
}

function handleClose() {
  form.value.categoryName = "";
  form.value.description = "";
  dialogVisible.value = false;
}

async function handleSizeChange(val: number) {
  param.value.size = val;
  await getGameCategoryListData(param.value);
}

async function handleCurrentChange(val: number) {
  param.value.page = val;
  await getGameCategoryListData(param.value);
}

async function getGameCategoryListData(param: any) {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  try {
    const res = await getCategoryList(param);
    gameCategoryList.value = res.data.records;
    pageCount.value = res.data.pages;
  } catch (error) {
    console.log(error);
  } finally {
    loading.close();
  }
}

function searchResult(data: any) {
  gameCategoryList.value = data.records;
}

onMounted(async () => {
  await getGameCategoryListData(param.value);
});
</script>

<style scoped>
:deep(.el-table__body tr) {
  height: 80px; /* 设置行高 */
}

.category-m-index {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.image {
  width: 100%;
  aspect-ratio: 1 / 1;
}

.pagination {
  position: relative;
  bottom: 0;
  /* height: 10vh; */
  margin: 10px auto;
}

.btn-group {
  margin-bottom: 1em;
}
</style>
